
package com.quirqy.servlet;


import java.io.IOException;
import java.util.List;
import java.util.ArrayList;


import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.persistence.EntityManager; 

//jackson for JSON support ? necessary?

import org.codehaus.jackson.map.ObjectMapper;

import com.quirqy.model.Person;
import com.quirqy.persistence.EMF;

public class PersonServlet extends HttpServlet {
  
  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws IOException {
      
	EntityManager em = EMF.get().createEntityManager();
        
	List<Person> users = new ArrayList<Person>();;
	try
	{             
		String path = req.getPathInfo();
		if ((path !=null) &&(path.endsWith("/")))
    	{
			path = path.substring(0, path.length() - 1);
		}
		//Does the path contain an Id for single object lookup?
        if (
        	((path !=null) &&
        	(path.matches("/\\d+")))
        	)
        {
        	//make sure the final char is not /
        	
			
        	String sId = path.substring(path.lastIndexOf('/')+1);
            Person pOrig = em.find(Person.class, Long.parseLong(sId));
             
            users.add(pOrig);
        }
        //The path is assumed to be looking for all items
        else 
        {
            javax.persistence.Query query = em.createQuery("select p from Person p ");
            users = (List<Person>)query.getResultList();
        }
	} finally {
		em.close();
	}
		ObjectMapper mapper = new ObjectMapper();
		resp.setContentType("application/json");
		mapper.writeValue(resp.getWriter(), users);
	}
  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws IOException {
      
      //accept the request body as json, and use
      // jackson library to produce a Person object.
      // add that person object to DB, and if successful,
      // return 201.
	int iResponseCode = resp.SC_INTERNAL_SERVER_ERROR;
	EntityManager em = EMF.get().createEntityManager();
	
	try
	{	
		String path = req.getPathInfo(); 
		
			
		if (
		(path !=null) &&
		(path.matches("/\\d+"))
		)
		{
			//trying to create at an item level.
		}	
		else
		{
			
			Person pOrig = null;
			
			if ((path != null) && (path.length()>1) )
			{
				//it is a multiple item update. Work to be done here...
				String sId = path.substring(path.lastIndexOf('/')+1);
				pOrig = em.find(Person.class, Long.parseLong(sId));
			}
			//Only add if item does not already exist.
			if (pOrig == null)
			{	
			
				//So the hole in this logic is it assumes only 1 item has been
				//posted, which is not likely realistic....
				ObjectMapper mapper = new ObjectMapper();
				Person p = mapper.readValue(req.getReader(), Person.class);
	
				em.getTransaction().begin();
				em.persist(p);
			    em.flush();
				em.getTransaction().commit();
				iResponseCode = resp.SC_CREATED;
			}
			else
			{
				//the guy is trying to add a person that already exists...can you believe that?
				iResponseCode = resp.SC_NOT_ACCEPTABLE;
			}
		}
	}
	catch (Exception e)
	{
		iResponseCode = resp.SC_INTERNAL_SERVER_ERROR;;
		resp.getWriter().print(e.getMessage());
	}
	finally
	{
	    em.close();
	}
	
	
	
	resp.setStatus(iResponseCode);
  }
  @Override
  public void doPut(HttpServletRequest req, HttpServletResponse resp)
      throws IOException {

    int iResponseCode = resp.SC_INTERNAL_SERVER_ERROR;
   EntityManager em = EMF.get().createEntityManager();


//WHAT ABOUT PUTTING AN ARRAY OF PEOPLE?
//REST SVS MUST PULL THE ID FROM THE URL
	try
	{
		String path = req.getPathInfo();
		
		
	 	//IF THE URL CONTAINS AN ID, IT IS A SINGLE ITEM UPDATE
		if (
		(path !=null) &&
		(path.matches("/\\d+"))
		)
		{
			
			String sId = path.substring(path.lastIndexOf('/')+1);
			Person pOrig = em.find(Person.class, Long.parseLong(sId));
			//if the item is found, it may be updated.
			if (pOrig != null)
			{
				
				
				ObjectMapper mapper = new ObjectMapper();
				Person p = mapper.readValue(req.getReader(), Person.class);
				pOrig.setEmail(p.getEmail());
				pOrig.setName(p.getName());
				pOrig.setPassword(p.getPassword());

				
				em.getTransaction().begin();
				em.merge(pOrig); 
				em.getTransaction().commit();
				
				iResponseCode = resp.SC_OK;
			}
		}	
		else
		{
			//it is a multiple item update. Work to be done here...
		}
	}
	catch (Exception e)
	{
		iResponseCode = resp.SC_INTERNAL_SERVER_ERROR;;
		resp.getWriter().print(e.getMessage());
	}
	finally
	{
	    em.close();
	}

	resp.setStatus(iResponseCode);
  }
  @Override
  public void doDelete(HttpServletRequest req, HttpServletResponse resp)
      throws IOException 
	{
      
      
		int iResponseCode = resp.SC_INTERNAL_SERVER_ERROR;
		EntityManager em = EMF.get().createEntityManager();

		try
		{
			String path = req.getPathInfo();
		
		
		 	//IF THE URL CONTAINS AN ID, IT IS A SINGLE ITEM UPDATE
			if (
			(path !=null) &&
			(path.matches("/\\d+"))
			)
			{	
				String sId = path.substring(path.lastIndexOf('/')+1);
				Person pOrig = em.find(Person.class, Long.parseLong(sId));
				//if the item is found, it may be deleted.
				if (pOrig != null)
				{
					em.getTransaction().begin();
					em.remove(pOrig); 
					em.getTransaction().commit();
					iResponseCode = resp.SC_OK;
				}
			}
		}
		catch (Exception e)
		{
			iResponseCode = resp.SC_INTERNAL_SERVER_ERROR;;
			resp.getWriter().print(e.getMessage());
		}
		finally
		{
			em.close();
		}

		resp.setStatus(iResponseCode);
	
	}
}
